<template>
	<view class="my-info-container">
		<!-- 自定义导航栏 -->
		<scroll-view class="content-scroll" scroll-y>
			<!-- 头像上传 -->
			<view class="section">
				<view class="avatar-section">
					<image class="avatar-preview" :src="formData.avatar || '/static/logo.png'" mode="aspectFill"
						@tap="chooseAvatar"></image>
					<text class="avatar-tip" @tap="chooseAvatar">点击更换头像</text>
				</view>
			</view>

			<!-- 基本信息 -->
			<view class="section">
				<view class="section-label">昵称</view>
				<input class="input-field" v-model="formData.nickname" placeholder="请输入昵称" maxlength="20" />
			</view>

			<view class="section">
				<view class="section-label">用户名</view>
				<input class="input-field" v-model="formData.username" placeholder="请输入用户名" maxlength="50" />
			</view>

			<view class="section">
				<view class="section-label">邮箱</view>
				<input class="input-field" v-model="formData.email" type="email" placeholder="请输入邮箱" />
			</view>

			<view class="section">
				<view class="section-label">手机号</view>
				<input class="input-field" v-model="formData.phone" type="number" placeholder="请输入手机号" maxlength="11" />
			</view>

			<!-- 个人信息 -->
			<view class="section">
				<view class="section-label">性别</view>
				<view class="gender-options">
					<view class="gender-item" :class="{ active: formData.gender === 'male' }"
						@tap="formData.gender = 'male'">
						<text>男</text>
					</view>
					<view class="gender-item" :class="{ active: formData.gender === 'female' }"
						@tap="formData.gender = 'female'">
						<text>女</text>
					</view>
					<view class="gender-item" :class="{ active: formData.gender === 'other' }"
						@tap="formData.gender = 'other'">
						<text>其他</text>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="section-label">生日</view>
				<picker mode="date" :value="formData.birthday" @change="onBirthdayChange" :end-date="getTodayDate()">
					<view class="picker-field">
						<text :class="{ placeholder: !formData.birthday }">
							{{ formData.birthday || '请选择生日' }}
						</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>

			<view class="section">
				<view class="section-label">个人简介</view>
				<textarea class="textarea-field" v-model="formData.bio" placeholder="介绍一下自己吧~" maxlength="200"
					:auto-height="true" />
				<view class="char-count">{{ formData.bio?.length || 0 }}/200</view>
			</view>

			<!-- 保存按钮 -->
			<view class="save-section">
				<button class="save-btn" :class="{ disabled: !canSave || saving }" @tap="handleSave"
					:disabled="!canSave || saving">
					{{ saving ? '保存中...' : '保存' }}
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { updateUser, type UserInfo, type UpdateUserParams } from '@/api/auth'
import { uploadFile } from '@/api/works'
import { USER_INFO_KEY, TOKEN_KEY } from '@/config/env'

// 表单数据
const formData = ref<UpdateUserParams & { id?: number }>({
	nickname: '',
	username: '',
	email: '',
	phone: '',
	gender: undefined,
	birthday: '',
	bio: '',
	avatar: ''
})

// 原始数据（用于对比是否有修改）
const originalData = ref<UpdateUserParams & { id?: number }>({})

// 保存状态
const saving = ref(false)

// 是否可以保存
const canSave = computed(() => {
	// 检查是否有修改
	const hasChanges = JSON.stringify(formData.value) !== JSON.stringify(originalData.value)
	// 检查必填字段
	const hasRequiredFields = formData.value.username && formData.value.username.length >= 3
	return hasChanges && hasRequiredFields
})

// 获取今天的日期（用于限制生日选择）
const getTodayDate = () => {
	const today = new Date()
	const year = today.getFullYear()
	const month = String(today.getMonth() + 1).padStart(2, '0')
	const day = String(today.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}

// 生日选择
const onBirthdayChange = (e: any) => {
	formData.value.birthday = e.detail.value
}

// 选择头像
const chooseAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0]

			try {
				uni.showLoading({ title: '上传中...', mask: true })

				// 上传头像
				const avatarUrl = await uploadFile(tempFilePath, 'image')

				formData.value.avatar = avatarUrl

				uni.hideLoading()
				uni.showToast({
					title: '头像上传成功',
					icon: 'success'
				})
			} catch (error: any) {
				uni.hideLoading()
				uni.showToast({
					title: error.message || '头像上传失败',
					icon: 'none'
				})
			}
		},
		fail: (err) => {
			console.error('选择图片失败:', err)
		}
	})
}

// 加载用户信息
const loadUserInfo = () => {
	try {
		const storedUserInfo = uni.getStorageSync(USER_INFO_KEY)
		if (storedUserInfo) {
			const userInfo: UserInfo = typeof storedUserInfo === 'string'
				? JSON.parse(storedUserInfo)
				: storedUserInfo

			// 填充表单数据
			formData.value = {
				id: userInfo.id,
				nickname: userInfo.nickname || '',
				username: userInfo.username || '',
				email: userInfo.email || '',
				phone: userInfo.phone || '',
				avatar: userInfo.avatar || '',
				gender: userInfo.gender || '', // 需要从后端获取
				birthday: userInfo.birthday || '', // 需要从后端获取
				bio: userInfo.bio || '' // 需要从后端获取
			}

			// 保存原始数据
			originalData.value = JSON.parse(JSON.stringify(formData.value))
		} else {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	} catch (error) {
		console.error('加载用户信息失败:', error)
		uni.showToast({
			title: '加载用户信息失败',
			icon: 'none'
		})
	}
}

// 保存用户信息
const handleSave = async () => {
	if (!canSave.value || saving.value) {
		return
	}

	if (!formData.value.id) {
		uni.showToast({
			title: '用户信息不完整',
			icon: 'none'
		})
		return
	}

	// 验证邮箱格式
	if (formData.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.value.email)) {
		uni.showToast({
			title: '邮箱格式不正确',
			icon: 'none'
		})
		return
	}

	// 验证手机号格式
	if (formData.value.phone && !/^1[3-9]\d{9}$/.test(formData.value.phone)) {
		uni.showToast({
			title: '手机号格式不正确',
			icon: 'none'
		})
		return
	}

	saving.value = true

	try {
		// 准备更新数据（排除 id）
		const { id, ...updateParams } = formData.value

		// 如果某些字段为空字符串，设置为 undefined（不更新）
		Object.keys(updateParams).forEach(key => {
			if (updateParams[key as keyof UpdateUserParams] === '') {
				updateParams[key as keyof UpdateUserParams] = undefined
			}
		})

		// 调用更新接口
		const updatedUser = await updateUser(id!, updateParams)

		// 更新本地存储
		uni.setStorageSync(USER_INFO_KEY, JSON.stringify(updatedUser.data))

		// 更新原始数据
		originalData.value = JSON.parse(JSON.stringify(formData.value))

		uni.showToast({
			title: '保存成功',
			icon: 'success'
		})

		// 延迟返回，让用户看到成功提示
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	} catch (error: any) {
		console.error('保存用户信息失败:', error)
		uni.showToast({
			title: error.message || '保存失败，请重试',
			icon: 'none',
			duration: 2000
		})
	} finally {
		saving.value = false
	}
}

// 返回
const goBack = () => {
	// 检查是否有未保存的修改
	const hasChanges = JSON.stringify(formData.value) !== JSON.stringify(originalData.value)

	if (hasChanges) {
		uni.showModal({
			title: '提示',
			content: '有未保存的修改，确定要离开吗？',
			success: (res) => {
				if (res.confirm) {
					uni.navigateBack()
				}
			}
		})
	} else {
		uni.navigateBack()
	}
}

// 页面加载
onMounted(() => {
	loadUserInfo()
})
</script>

<style scoped>
.my-info-container {
	width: 100%;
	height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}

/* 自定义导航栏 */
.custom-navbar {
	background-color: #fff;
	padding-top: var(--status-bar-height, 20px);
	border-bottom: 1rpx solid #eee;
	position: sticky;
	top: 0;
	z-index: 100;
}


/* 内容区域 */
.content-scroll {
	flex: 1;
	overflow-y: auto;
}

/* 区块 */
.section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 20rpx;
}

/* 头像区域 */
.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
}

.avatar-preview {
	width: 200rpx;
	height: 200rpx;
	border-radius: 50%;
	border: 4rpx solid #f0f0f0;
}

.avatar-tip {
	font-size: 24rpx;
	color: #4A90E2;
}

/* 输入框 */
.input-field {
	width: 100%;
	height: 80rpx;
	padding: 0 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	color: #000;
	font-weight: 600;
}

/* 性别选择 */
.gender-options {
	display: flex;
	gap: 20rpx;
}

.gender-item {
	flex: 1;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	border: 2rpx solid transparent;
	font-size: 28rpx;
	color: #666;
}

.gender-item.active {
	background-color: #c5c3c3;
	border-color: #000;
	color: #000;
	font-weight: 600;
}

/* 选择器 */
.picker-field {
	width: 100%;
	height: 80rpx;
	padding: 0 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 28rpx;
	color: #000;
	font-weight: 600;
}

.picker-field .placeholder {
	color: #999;
}

.picker-arrow {
	color: #999;
	font-size: 24rpx;
}

/* 文本域 */
.textarea-field {
	width: 100%;
	min-height: 200rpx;
	padding: 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #000;
	font-weight: 600;
	line-height: 1.6;
}

.char-count {
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}

/* 保存按钮区域 */
.save-section {
	padding: 40rpx 30rpx;
	background-color: #fff;
	margin-top: 20rpx;
	margin-bottom: 40rpx;
}

.save-btn {
	width: 100%;
	height: 88rpx;
	background: #000;
	border-radius: 44rpx;
	color: #fff;
	font-size: 32rpx;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
}

.save-btn.disabled {
	background: #4a4a4a;
	color: #999;
}

.save-btn::after {
	border: none;
}
</style>
